/**
 * Created by Datura on 2017/3/8 0008.
 */
/**
 *数据库操作辅助类,定义对象、数据操作方法都在这里定义
 */
var dbname = 'websql'; /*数据库名*/
var version = ''; /*数据库版本*/
var dbdesc = 'Datura练习'; /*数据库描述*/
var dbsize = 40 * 1024 * 1024; /*数据库大小*/
var dataBase = null; /*暂存数据库对象*/
/*数据库中表的名*/
var sbInfoTable = "sbInfoTable";
var jcxInfoTable = "jcxInfoTable";
var uptime;
var upTime;
/**
 * 打开数据库
 * dataBase:打开成功   null:打开失败
 */
//获取数据库版本号  
   


function websqlOpenDB() {
	/*数据库有就打开 没有就创建*/
	dataBase = window.openDatabase(dbname, version, dbdesc, dbsize, function() {});
	if(dataBase) {
		console.log("数据库创建/打开成功!");
	} else {
		console.log("数据库创建/打开失败！");
	}
	return dataBase;
}
/**
 * 新建数据库里面的表单
 * tableName:表单名
 */
        /*var dbObj = websqlOpenDB();
        alert('shuju'+dbObj.version);*/
 var org_code = localStorage.getItem('org_code'); //获取缓存中的风场编号
var org_code1 = JSON.parse(org_code);
//获取时间
function time(type){
mui.baseApp.httpRequst('/api/v2/sbxj/updateRecord', {
	wind: org_code1
}, function(res) {
	if(res.status == 200) {	
		console.log("时间接口" + JSON.stringify(res));
		upTime = localStorage.getItem("upTime");
		uptime = res.data;
		// uptime = res.data || 'noupdate';
		// if(upTime && upTime == 'noupdate' && uptime == 'noupdate'){
		// 	mui.toast('该风场设备数据未进行修改！');
		// 	return;
		// }
		console.log(upTime)
		console.log(uptime)
		//存入更新时间
		localStorage.setItem('upTime', uptime);
		websqladddata(uptime,upTime,type);
	}
})

}
//websqladddata();
//有网状态下判断添加数据
// websqlOpenDB();
function websqladddata(uptime,upTime,type) {
	var dataBase = websqlOpenDB();
	
	//判断某表是否存在：表名 
	var sql = "select * from sqlite_master where type='table' and name = ?";
	dataBase.transaction(function(tx) {
		tx.executeSql(sql, [sbInfoTable], function(transaction, result) {
			if(result.rows.length > 0) {
				if(uptime == upTime) {
					if(type==1){
						setTimeout(function(){
							if(document.getElementById('progressbar-div')==null)
							mui.toast('您已经是最新数据了！');
						},1000)
					}else{
						
					}
				} else {
					dataBase.transaction(function(tx) {
						tx.executeSql('drop  table  sbInfoTable');
//						alert('sbInfoTable');
					});
					websqlCreatTable(sbInfoTable);
					instersbInfoTable();
				}
			} else if(result.rows.length <= 0) {
				websqlCreatTable(sbInfoTable);
				instersbInfoTable();
			}
		}, null);
	});
	dataBase.transaction(function(tx) {
		tx.executeSql(sql, [jcxInfoTable], function(transaction, result) {
			if(result.rows.length > 0) {
				if(uptime == upTime) {
//					mui.toast('数据不需要更新');
				} else {
					dataBase.transaction(function(tx) {
						tx.executeSql('drop  table  jcxInfoTable');
//						alert('jcxInfoTable');
					});
					websqlCreatTable_(jcxInfoTable);
					setTimeout("insterjcxInfoTable()","1000");
//					insterjcxInfoTable();
					
				}
			} else if(result.rows.length <= 0) {
				websqlCreatTable_(jcxInfoTable);
				setTimeout("insterjcxInfoTable()","1000");
//				insterjcxInfoTable();
			}
		}, null);
	});
}
//插入第一个表数据
function  instersbInfoTable()  {  
	var wt = plus.nativeUI.showWaiting('数据同步中...');           
	console.log("插入数据"); 
	mui.baseApp.httpRequst('/api/v2/sbxj/syncData', {
		userid: localStorage.getItem('userid')
	}, function(res) {
		console.log("存入接口数据" + JSON.stringify(res));
		if(res.status == 200) {
			//循环res后台传过来的数据。
			var sbInfo = res.data.sbInfo;
			console.log("sbInfo" + JSON.stringify(sbInfo))
			for(var i = 0; i < sbInfo.length; i++) {
				var create_time = sbInfo[i].create_time;
				var name = sbInfo[i].name;
				var id = sbInfo[i].id;
				var member_id = sbInfo[i].member_id;
				var sancode = sbInfo[i].number;
				var qrcode = sbInfo[i].qrcode;
				var rate = sbInfo[i].rate;
				var rateid = sbInfo[i].rateid;
				var status = sbInfo[i].status;
				var tell = sbInfo[i].tell;
				var templat_id = sbInfo[i].templat_id;
				var type = sbInfo[i].type;
				var wind = sbInfo[i].wind;
				var windname = sbInfo[i].windname;
				var membername = sbInfo[i].membername;
				var values = [create_time, id, member_id, sancode, qrcode, rate, rateid, status, tell, templat_id, type, wind];
				//console.log('values' + values)
				websqlInsterDataToTable(sbInfoTable, create_time, name, id, member_id, sancode, qrcode, rate, rateid, status, tell, templat_id, type, wind, windname, membername);
			}
			wt.close();

		} else if(res.data == 400) {
			mui.toast('密码不正确!');
		} else if(res.data == 409) {
			mui.toast('用户不存在!');
		}

		console.log('数据下载成功');
		//		wt.close;
	}) 
}
//插入第二个表数据
function  insterjcxInfoTable()  { 
	var wt = plus.nativeUI.showWaiting('数据加载中...');;           
	console.log("插入数据"); 
	mui.baseApp.httpRequst('/api/v2/sbxj/syncData', {
		userid: localStorage.getItem('userid')
	}, function(res) {
		console.log("存入接口数据" + JSON.stringify(res));
		if(res.status == 200) {
			//循环res后台传过来的数据。
			//						循环插入第二个表
			var jcxInfo = res.data.jcxInfo;
			for(var j = 0; j < jcxInfo.length; j++) {
				var id = jcxInfo[j].id;
				var mbmx_id = jcxInfo[j].mbmx_id;
				var name = jcxInfo[j].name;
				var rateid = jcxInfo[j].rateid;
				var standard = jcxInfo[j].standard;
				var rateid = jcxInfo[j].rateid;
				var type = jcxInfo[j].type;
				var desc_name = jcxInfo[j].desc_name;
				var unit = jcxInfo[j].unit;
				var values = [jcxInfoTable, id, mbmx_id, name, rateid, standard, type,desc_name,unit];
				//							console.log('value2222222' + values)
				websqlInsterDataToTable_(jcxInfoTable, id, mbmx_id, name, rateid, standard, type,desc_name,unit);
			}
			wt.close();

		} else if(res.data == 400) {
			mui.toast('密码不正确!');
		} else if(res.data == 409) {
			mui.toast('用户不存在!');
		}

		mui.toast('数据同步成功~~');
		//		wt.close;
	}) 
}

function websqlCreatTable(tableName) {
	var creatTableSQL = 'CREATE TABLE IF  NOT EXISTS ' + tableName + ' (CREATE_TIME,NAME,ID,MEMBER_ID,SANCODE,QRCODE,RATE,RATEID,STATUS,TELL,TEMPLAT_ID,TYPE,WIND,WINDNAME,MEMBERNAME)';
	dataBase.transaction(function(ctx, result) {
		ctx.executeSql(creatTableSQL, [], function(ctx, result) {
			console.log("表创建成功 " + tableName);
		}, function(tx, error) {
			console.log('创建表失败:' + tableName + error.message);
		});
	});
}

function websqlInsterDataToTable(tableName, CREATE_TIME, NAME, ID, MEMBER_ID, SANCODE, QRCODE, RATE, RATEID, STATUS, TELL, TEMPLAT_ID, TYPE, WIND, WINDNAME, MEMBERNAME) {
	var insterTableSQL = 'INSERT INTO ' + tableName + ' (CREATE_TIME,NAME,ID,MEMBER_ID,SANCODE,QRCODE,RATE,RATEID,STATUS,TELL,TEMPLAT_ID,TYPE,WIND,WINDNAME,MEMBERNAME) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';
	dataBase.transaction(function(ctx) {
		ctx.executeSql(insterTableSQL, [CREATE_TIME, NAME, ID, MEMBER_ID, SANCODE, QRCODE, RATE, RATEID, STATUS, TELL, TEMPLAT_ID, TYPE, WIND, WINDNAME, MEMBERNAME], function(ctx, result) {
				console.log("插入" + tableName + MEMBER_ID + "成功");
			},
			function(tx, error) {
				console.log('插入失败: ' + error.message);
			});
	});
}

/**
 * 获取数据库一个表单里面的所有数据
 * tableName:表单名
 * 返回数据集合
 */
function websqlGetAllData(tableName) {
	var selectALLSQL = 'SELECT * FROM ' + tableName;
	dataBase.transaction(function(ctx) {
		ctx.executeSql(selectALLSQL, [], function(ctx, result) {
				console.log('查询成功: ' + tableName + result.rows.length);
				var len = result.rows.length;
				for(var i = 0; i < len; i++) {
//					console.log("CREATE_TIME = " + JSON.stringify(result.rows.item(i)));
					/*console.log("AGE = "  + result.rows.item(i).AGE);
					console.log("HEIGHT = "  + result.rows.item(i).HEIGHT);
					console.log("WEIGTH = "  + result.rows.item(i).WEIGTH);*/
//					console.log("-------- 我是分割线 -------");
				}
			},
			function(tx, error) {
				alert('查询失败: ' + error.message);
			});
	});
}

/**
 * 删除表单里的全部数据
 * tableName:表单名
 */
function websqlDeleteAllDataFromTable(tableName) {
	var deleteTableSQL = 'DELETE FROM ' + tableName;
	localStorage.removeItem(tableName);
	dataBase.transaction(function(ctx, result) {
		ctx.executeSql(deleteTableSQL, [], function(ctx, result) {
			console.log("删除表成功 " + tableName);
		}, function(tx, error) {
			console.log('删除表失败:' + tableName + error.message);
		});
	});
}
/**
 * 根据name删除数据
 * tableName:表单名
 * name:数据的姓名
 */
function websqlDeleteADataFromTable(tableName, name) {
	var deleteDataSQL = 'DELETE FROM ' + tableName + ' WHERE NAME = ?';
	localStorage.removeItem(tableName);
	dataBase.transaction(function(ctx, result) {
		ctx.executeSql(deleteDataSQL, [name], function(ctx, result) {
			console.log("删除成功 " + tableName + name);
		}, function(tx, error) {
			console.log('删除失败:' + tableName + name + error.message);
		});
	});
}
/**
 * 根据name修改数据
 * tableName:表单名
 * name:姓名
 * age:年龄
 */
function websqlUpdateAData(tableName, name, age) {
	var updateDataSQL = 'UPDATE ' + tableName + ' SET AGE = ? WHERE NAME = ?';
	dataBase.transaction(function(ctx, result) {
		ctx.executeSql(updateDataSQL, [age, name], function(ctx, result) {
			console.log("更新成功 " + tableName + name);
		}, function(tx, error) {
			console.log('更新失败:' + tableName + name + error.message);
		});
	});
}

var sbInfo_ = {
	"List": {}
};
//查找设备信息
function websqlGetAData(tableName, scancode, rate) {
	sbInfo_.List = {};
	var selectSQL = 'SELECT * FROM ' + tableName + ' WHERE SANCODE = ? AND RATE= ?'
	dataBase.transaction(function(ctx) {
		ctx.executeSql(selectSQL, [scancode, rate], function(ctx, result) {
				console.log('查询成功tableName: ' + tableName + result.rows.length);
				var len = result.rows.length;
				for(var i = 0; i < len; i++) {
					console.log("number = " + result.rows.item(i).SANCODE);
					console.log("RATE = " + result.rows.item(i).RATE);
					console.log("rateid = " + result.rows.item(i).RATEID);
					var name = result.rows.item(i).NAME;
					var create_time = result.rows.item(i).CREATE_TIME;
					var status = result.rows.item(i).STATUS;
					var membername = result.rows.item(i).MEMBERNAME;
					var tell = result.rows.item(i).TELL;
					var windname = result.rows.item(i).WINDNAME;
					var type = result.rows.item(i).TYPE;
					var number = result.rows.item(i).SANCODE;
					var rateid = result.rows.item(i).RATEID;
					sbInfo_.List = {
						"name": name,
						"create_time": create_time,
						"status": status,
						"tell": tell,
						"type": type,
						"number": number,
						"windname": windname,
						"membername": membername,
						"rateid": rateid						
					}

					console.log('1...........'+JSON.stringify(sbInfo_.List));
				}
				console.log(JSON.stringify(sbInfo_));
				if(sbInfo_ != undefined) {
					success(sbInfo_);
				}

			},
			function(tx, error) {
				alert('查询失败: ' + error.message);
			});
	});
	return sbInfo_;

}

//第二个表
function websqlCreatTable_(tableName) {
	var creatTableSQL = 'CREATE TABLE IF  NOT EXISTS ' + tableName + ' (ID,MBMX_ID,NAME,RATEID,STANDARD,TYPE,DESCNAME,UNIT)';
	dataBase.transaction(function(ctx, result) {
		ctx.executeSql(creatTableSQL, [], function(ctx, result) {
			console.log("表创建成功 " + tableName);
		}, function(tx, error) {
			console.log('创建表失败:' + tableName + error.message);
		});
	});
}

function websqlInsterDataToTable_(tableName, ID, MBMX_ID, NAME, RATEID, STANDARD, TYPE,DESCNAME,UNIT) {
	var insterTableSQL = 'INSERT INTO ' + tableName + ' (ID,MBMX_ID,NAME,RATEID,STANDARD,TYPE,DESCNAME,UNIT) VALUES (?,?,?,?,?,?,?,?)';
	dataBase.transaction(function(ctx) {
		ctx.executeSql(insterTableSQL, [ID, MBMX_ID, NAME, RATEID, STANDARD, TYPE,DESCNAME,UNIT], function(ctx, result) {
				// console.log("插入" + tableName + MBMX_ID + "成功");
			},
			function(tx, error) {
				alert('插入失败: ' + error.message);
			});
	});
}
//查询第二个表数据
var jcxInfo = {
	"List": []
};

function websqlGetAData_(tableName, rateid) {
	jcxInfo.List = [];
	console.log('rateid：' + rateid);
	var selectSQL = 'SELECT * FROM ' + tableName + ' WHERE RATEID = ?'
	dataBase.transaction(function(ctx) {
		ctx.executeSql(selectSQL, [rateid], function(ctx, result) {
				console.log('查询成功jcxInfoTable: ' + tableName + result.rows.length);
				//              alert(rateid);
				var len = result.rows.length;
				for(var i = 0; i < len; i++) {
					console.log("第二个表条件查询 " + JSON.stringify(result.rows.item(i)));
					var id = result.rows.item(i).ID;
					var rateid = result.rows.item(i).RATEID;
					var mbmx_id = result.rows.item(i).MBMX_ID;
					var standard = result.rows.item(i).STANDARD;
					var name = result.rows.item(i).NAME;
					var type = result.rows.item(i).TYPE;
					var desc_name = result.rows.item(i).DESCNAME;
					var unit = result.rows.item(i).UNIT;
					list = {
						"name": name,
						"id": id,
						"mbmx_id": mbmx_id,
						"standard": standard,
						"rateid": rateid,
						"type": type,
						"desc_name": desc_name,
						"unit": unit
					}
					jcxInfo.List.push(list);
					console.log(JSON.stringify(jcxInfo.List));

				}
				if(jcxInfo != undefined) {
					success_(jcxInfo);
				}
			},
			function(tx, error) {
				alert('查询失败: ' + error.message);
			});
	});
}

 //修改数据库版本信息  
    function changeDBVersion(oldVersion, newVersion) {  
       var dataBase = websqlOpenDB();  
        dataBase.changeVersion(oldVersion, newVersion, null, null, null);  
    }
    getVersion();
    function getVersion(oldVersion, newVersion) {  
        var dataBase = websqlOpenDB();
        
        console.log('数据库版本'+dataBase.version);
        return dataBase.version; 
    }